Laravel
Models Migration Relation
Introduction,istallation Strucutre,model,migration Migration,Models,Relation
Les Relations
BelongsTo HasOne HasMany BelongsToMany HasManyThrough
Exemples des Relations
Relations:oneToMany,ManyToMany... Relations:Exemples
Exercices
Exercice 1 Exercice 2
Controllers Views Routes
Routes,Controller,Model,view CRUD: Etudiant CRUD: Car CRUD,Recherche: Book
Validation
Exemple :Projets
Api:Laravel +React
Middleware

Seeders & Factories

Authenfication
Layouts





La relation "HasOne" dans Laravel

Exemple 1
une application de blog, où un utilisateur a un seul profil. Les tables associées sero nt users et profiles.
Migration pour la table users :
// database/migrations/YYYY_MM_DD_create_users_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id('id'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}
Migration pour la table profiles :
// database/migrations/YYYY_MM_DD_create_profiles_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->id('idProfile'); // Nommer la clé primaire avec idTable
            $table->string('bio')->nullable();
            $table->string('avatar')->nullable();
            $table->unsignedBigInteger('user_id')->unique(); // Clé étrangère et unique

            $table->foreign('user_id')->references('id')->on('users');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('profiles');
    }
}
Modèle pour la table User :
// app/Models/User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'email', 'password'];

    public function profile()
    {
        return $this->hasOne(Profile::class, 'user_id', 'id');
    }
}
Modèle pour la table Profile :
// app/Models/Profile.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    protected $table = 'profiles';
    protected $primaryKey = 'idProfile'; // Nommer la clé primaire avec idTable
    protected $fillable = ['bio', 'avatar', 'user_id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}
Dans cet exemple, un utilisateur (User) a un profil (Profile). La table profiles contient une clé étrangère user_id qui fait référence à la clé primaire id dans la table des utilisateurs. La méthode profile() dans le modèle User définit la relation "HasOne", tandis que la méthode user() dans le modèle Profile définit la relation "BelongsTo". Vous pouvez ensuite accéder au profil associé à un utilisateur ou à l'utilisateur associé à un profil de la manière suivante :
Exemple 2
exemple de la relation "HasOne" dans le contexte d'une application de magasin en ligne, où chaque produit peut avoir une seule fiche technique. Les tables associées seront products et specifications.
Migration pour la table products :
// database/migrations/YYYY_MM_DD_create_products_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id('idProduct'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->text('description');
            $table->decimal('price', 8, 2);
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('products');
    }
}
Migration pour la table specifications :
// database/migrations/YYYY_MM_DD_create_specifications_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('specifications', function (Blueprint $table) {
            $table->id('idSpecification'); // Nommer la clé primaire avec idTable
            $table->text('details');
            $table->unsignedBigInteger('product_id')->unique(); // Clé étrangère et unique

            $table->foreign('product_id')->references('idProduct')->on('products');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('specifications');
    }
}
Modèle pour la table Product :
// app/Models/Product.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    protected $primaryKey = 'idProduct'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'description', 'price'];

    public function specification()
    {
        return $this->hasOne(Specification::class, 'product_id', 'idProduct');
    }
}
Modèle pour la table Specification :
// app/Models/Specification.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Specification extends Model
{
    protected $table = 'specifications';
    protected $primaryKey = 'idSpecification'; // Nommer la clé primaire avec idTable
    protected $fillable = ['details', 'product_id'];

    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'idProduct');
    }
}
Exemple 3
une application de gestion d'événements, où chaque événement a un emplacement spécifique. Les tables associées seront events et locations.
Migration pour la table events :
// database/migrations/YYYY_MM_DD_create_events_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->id('idEvent'); // Nommer la clé primaire avec idTable
            $table->string('title');
            $table->text('description');
            $table->dateTime('start_date');
            $table->dateTime('end_date');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('events');
    }
}
Migration pour la table locations :
// database/migrations/YYYY_MM_DD_create_locations_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('locations', function (Blueprint $table) {
            $table->id('idLocation'); // Nommer la clé primaire avec idTable
            $table->string('name');
            $table->string('address');
            $table->string('city');
            $table->string('country');
            $table->unsignedBigInteger('event_id')->unique(); // Clé étrangère et unique

            $table->foreign('event_id')->references('idEvent')->on('events');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('locations');
    }
}
Modèle pour la table Event :
// app/Models/Event.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    protected $table = 'events';
    protected $primaryKey = 'idEvent'; // Nommer la clé primaire avec idTable
    protected $fillable = ['title', 'description', 'start_date', 'end_date'];

    public function location()
    {
        return $this->hasOne(Location::class, 'event_id', 'idEvent');
    }
}
Modèle pour la table Location :
// app/Models/Location.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Location extends Model
{
    protected $table = 'locations';
    protected $primaryKey = 'idLocation'; // Nommer la clé primaire avec idTable
    protected $fillable = ['name', 'address', 'city', 'country', 'event_id'];

    public function event()
    {
        return $this->belongsTo(Event::class, 'event_id', 'idEvent');
    }
}
Dans cet exemple, chaque événement (Event) a un emplacement spécifique (Location). La table locations contient une clé étrangère event_id qui fait référence à la clé primaire idEvent dans la table des événements. La méthode location() dans le modèle Event définit la relation "HasOne", tandis que la méthode event() dans le modèle Location définit la relation "BelongsTo".